package com.jxwifi.cloud.quickclean.assemble;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickclean.MainActivity;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.AStartResultBean;
import com.jxwifi.cloud.quickclean.bean.AssembleItemsBean;
import com.jxwifi.cloud.quickclean.bean.StrListBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.pay.PayUtil;
import com.jxwifi.cloud.quickclean.popwindow.PopPayDepositModule;
import com.jxwifi.cloud.quickclean.quicktreasure.BuySetMealActivity;
import com.jxwifi.cloud.quickclean.toolkit.BuyToolKitActivity;
import com.jxwifi.cloud.quickclean.utils.KAlertDialog;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.jxwifi.cloud.quickclean.utils.TokenTimeUtils;
import com.jxwifi.cloud.quickclean.utils.shareUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class AssembleDetailsPresenter {

    private String TAG = this.getClass().getSimpleName();
    private static final String  StrUrlDefult="https://kjb-oss.oss-cn-shenzhen.aliyuncs.com/ul9zg740a645wxjfxddl.png";

    private Context mContext;
    private AssembleDetailsView mView;
    private AuzImpl mAuz;

    private AssembleItemsBean mBean;
    private AStartResultBean mASBean;//支付参数请求后返回的数据， 支付成功后做页面数据刷新
    private CountDownTimer timer;

    public AssembleDetailsPresenter(Context context,AssembleDetailsView view){
        this.mContext=context;
        this.mView=view;
        mAuz=new AuzImpl();
    }

    public void initData(){
        Params params=new Params();
        params.add("joinType","start");
        params.add("optionCode",mView.getDetailsBean().getOptionCode());
        params.add("optionType",mView.getDetailsBean().getOptionType());
        params.add("serviceCode",mView.getDetailsBean().getServiceCode());
        mAuz.auzpost(UrlPool.ASSEMBLE_DETAILS, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                mBean= JSON.parseObject(data, AssembleItemsBean.class);
                //Log.i(TAG,"initData mBean ==> data1 = "+data);
                initView();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void initView(){
        mView.getLinAssembleDetails().setVisibility(View.VISIBLE);
        mView.getWebViewShow().setVisibility(View.VISIBLE);
        mView.getLinAssembleResult().setVisibility(View.GONE);
        mView.getDetailsSharIt().setVisibility(View.GONE);
        if (!TextUtils.isEmpty(mBean.getImgUrl())){
            Glide.with(mContext).load(mBean.getImgUrl()).into(mView.getDetailsImages());
        }else{
            Glide.with(mContext).load(StrUrlDefult).into(mView.getDetailsImages());
        }
        mView.getAllNumber().setText("拼单总人数:"+mView.getDetailsBean().getPsum()+"人");
        mView.getDetailsName().setText(mBean.getOptionName());
        DecimalFormat df = new DecimalFormat("#0.00");
        mView.getDetailsPrice().setText(""+df.format(mBean.getDiscountPrice()));
        mView.getOriginalPrice().setText("原价\u00A5"+mBean.getPrimeCost());
        mView.getOriginalPrice().getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        mView.getDescription().getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG ); //下划线
        mView.getDetailsGiveAway().setText(mBean.getAdditionalName()+""+mBean.getAdditionalValue());
        mView.getDetailsButton().setText("\u00A5"+df.format(mBean.getDiscountPrice())+"\n"+"发起拼团");
        mView.getDetailsBuy().setText("\u00A5"+mBean.getPrimeCost()+"\n"+"单独购买");
        if (!TextUtils.isEmpty(mBean.getSpecs())){
            mView.getSpecification().setVisibility(View.VISIBLE);
            List<StrListBean> mList = new ArrayList<>();
            mList = JSON.parseArray(mBean.getSpecs(), StrListBean.class);
            String Specifications = "";
            for (int i = 0; i < mList.size(); i++) {
                //Specifications = Specifications + "" + mList.get(i).getKey() + ":" + mList.get(i).getValue();
                if (i==0){
                    Specifications=mList.get(i).getKey()+"    "+mList.get(i).getValue();
                }else{
                    Specifications=Specifications+"\n"+mList.get(i).getKey()+"    "+mList.get(i).getValue();
                }
            }
            mView.getSpecification().setText(Specifications);
        }else{
            mView.getSpecification().setVisibility(View.GONE);
        }
        PhotoUrl();

    }


    public void assembleCancel(){
        Params params=new Params();
        params.add("orderCode",mASBean.getOrderCode());
        mAuz.auzpost(UrlPool.POST_CANCEL, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code==0){
                    Toast toast = Toast.makeText(mContext, "取消成功", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    //initData();
                    mView.onCancelSuccess();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }


    //原价购买
    public void payButIntenter(){
        Intent intent=new Intent();
        if (StateUtils.TD.equals(mBean.getOptionType())){ //清洁服务
            intent.setClass(mContext,MainActivity.class);
        }else if (StateUtils.SN.equals(mBean.getOptionType())){ //工具包
            intent.setClass(mContext,BuyToolKitActivity.class);

        }else if (StateUtils.SR.equals(mBean.getOptionType())){ //套餐
            intent.setClass(mContext,BuySetMealActivity.class);
        }
        mContext.startActivity(intent);
    }

    public void PhotoUrl() {
        mView.getWebViewShow().getSettings().setLoadWithOverviewMode(true);
            mView.getWebViewShow().getSettings().setDefaultTextEncodingName("UTF-8");
        StringBuilder sb = new StringBuilder();
        sb.append("<link rel=\"stylesheet\" href=\"file:///android_asset/common.css\" type=\"text/css\"/> ");
        sb.append("<div class=\"touch-detail\">");
        sb.append(mBean.getIntroduce());
        sb.append("</div>");

            mView.getWebViewShow().loadDataWithBaseURL("about:blank", sb.toString(), "text/html", "utf-8", null);
    }

    //支付弹框
    public void paySetMeal(){
        PopPayDepositModule mPopPayOrder = new PopPayDepositModule(mContext, Double.valueOf(mBean.getDiscountPrice()), "支付金额", new PopPayDepositModule.PopPayListener() {
            @Override
            public void getPayOrder(String PayType, String PayPrice) {
                initiateAssemble(PayType);
            }
        });
        Popwindows window = PopWindowUtil.getPopupWindow(mPopPayOrder.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        mPopPayOrder.setPopwindow(window);
        window.show(mView.getDescription(), Popwindows.Location.TOP);
    }

    //发起拼团
    public void initiateAssemble(String PayPrice){
        Params params=new Params();
        params.add("joinType","start");
        params.add("optionCode",mBean.getOptionCode());
        params.add("optionType",mBean.getOptionType());
        params.add("payChannelEnum",PayPrice);
        params.add("serviceCode",mBean.getServiceCode());
        params.add("tradeType","APP");
        mAuz.auzpost(UrlPool.ASSEMBLE_START, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                //AStartResultBean
                if (code==0){
                    mASBean = JSON.parseObject(data, AStartResultBean.class);
                    if (StateUtils.PAY_ALI.equals(mASBean.getPayPrepay().getPayChannelEnum())) { //支付宝
                        PayUtil.getInstance().aliPay(mContext, mASBean.getPayPrepay());
                    } else if (StateUtils.PAY_WX.equals(mASBean.getPayPrepay().getPayChannelEnum())) { //微信
                        //mView.getWXPayCode(mASBean.getPayPrepay().getOutTradNo());
                        PayUtil.getInstance().WXPay(mContext, mASBean.getPayPrepay().getWxPayResult());
                    }
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });

    }

    //支付成功刷新页面数据布局
    public void RefreshView(){
        mView.getDetailsButton().setVisibility(View.GONE);
        mView.getDetailsBuy().setVisibility(View.GONE);
        mView.getLinAssembleDetails().setVisibility(View.GONE);
        mView.getWebViewShow().setVisibility(View.GONE);
        mView.getLinAssembleResult().setVisibility(View.VISIBLE);
        mView.getDetailsSharIt().setVisibility(View.VISIBLE);
        mView.getDetailsCancel().setVisibility(View.VISIBLE);
        setTimerCount(mASBean.getSurplusTime());
        mView.getAllNumber().setText("拼单总人数:"+mASBean.getPersonNumber());
        mView.getOrTrue().setText("是否成团:未成团");
        mView.getNumbering().setText("拼单编号"+mASBean.getCdesk());
        mView.getDifference().setText("相差人数:"+(mASBean.getPersonNumber()-1)+"人");

        final KAlertDialog dialogshow=new KAlertDialog(mContext,"邀请好友加入拼团");
        dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {

                IWXAPI mIWXAPI = WXAPIFactory.createWXAPI(mContext, StateUtils.WX_APPID, false);
                mIWXAPI.registerApp(StateUtils.WX_APPID);
                weChatShare(mIWXAPI, 1, mContext);
                dialogshow.dismiss();
            }
        });
        dialogshow.show();

    }

    //倒计时操作
    private void setTimerCount(int surplusTime) {
        timer = new CountDownTimer(surplusTime *60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mView.getAssembleTime().setText("拼单剩余时间:"+ TokenTimeUtils.getSecondToDayHourMinutes(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                timer.cancel();
                mView.getAssembleTime().setText("拼单剩余时间:0天00:00:00");
            }
        };
        timer.start();
    }

    public void weChatShare(IWXAPI iwxapi, int flag, Context mContext){

        shareUtils.share2weixin(iwxapi,flag ,mContext,6,mASBean.getOrderCode(),mASBean.getCdesk());
    }


}
